<?php
/**
 * Created by PhpStorm.
 * User: 764432054@qq.com
 * Date: 2018/7/29
 * Time: 11:28
 * pcntl_waitpid()
 * 返回退出的子进程进程号，发生错误时返回-1,如果提供了 WNOHANG作为option（wait3可用的系统）并且没有可用子进程时返回0
 */
$pid=pcntl_fork();
if($pid<0){
   exit("fork error ".PHP_EOL);
}
//循环等待方式
/*
if($pid>0){
    cli_set_process_title("php_parent_".posix_getpid());
    while(true ){
        sleep(2); //子进程退出的刹那，父进程子啊休眠中，这段时间子进程成为僵尸进程
        $wait_res=pcntl_waitpid($pid,$status,WNOHANG);
        echo "pid=".var_export($pid,true)."--wait_res=".var_export($wait_res,true)."---status=".var_export($status,true).PHP_EOL;
        if($pid == $wait_res){
            echo "回收完毕！".PHP_EOL;
            break;
        }
    }
}elseif($pid==0){
    cli_set_process_title("php_son_".posix_getpid());
    sleep(10);
}
*/

//信号处理方式

if($pid>0){
    cli_set_process_title("php_parent_".posix_getpid());
    $wait_res=0;
    sleep(2);
    pcntl_signal(SIGCHLD,function() use($pid,&$wait_res){
        echo "收到".$pid."子进程退出".PHP_EOL;
        $wait_res=pcntl_waitpid($pid,$status,WNOHANG);
        echo "wait_Res=".var_export($wait_res,true)."--status=".var_export($status,true).PHP_EOL;
    });
    $i=0;

    sleep(5);
    print("parent sleep over!\n");
    while(true){
        $r=pcntl_signal_dispatch();
        echo $r."--".$i."--".$wait_res.PHP_EOL;
        sleep(1);
        if($wait_res!=0){
            break;
        }
        $i++;
    }
    //sleep(10);
    /*for($i=0;$i<5;$i++){
        echo "parent_".$i.PHP_EOL;
        sleep(1);
    }*/
    echo "parent_exit".PHP_EOL;

}else{
    cli_set_process_title("php_son_".posix_getpid());
    for($i=0;$i<5;$i++){
        echo "son_".$i.PHP_EOL;
        sleep(1);
    }
    echo "son_exit".PHP_EOL;
    exit;
}


